package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.interior.SearchList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;

public class ChangeProduct extends BaseRFIDActivity {

    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.tv_epc_new) TextView tv_epc_new;
    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.tv_FQty) TextView tv_FQty;
    @Bind(R.id.tv_FModel) TextView tv_FModel;
    @Bind(R.id.tv_FName_new) TextView tv_FName_new;
    @Bind(R.id.tv_FModel_new) TextView tv_FModel_new;
    @Bind(R.id.btn_query) Button btn_query;
    @Bind(R.id.at_FNumber_new) AutoCompleteTextView at_FNumber_new;

    private boolean scaning = false;
    private String epc = "";
    private int FItemID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_product);
        initBaseView();
        initView();
    }

    private void initView(){
        title.setText("改产品");
        ll_submit.setVisibility(View.VISIBLE);
        //查询新产品
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SearchList.class);
                intent.putExtra("keyword",at_FNumber_new.getText().toString());
                startActivityForResult(intent, 1);
            }
        });

        //提交
        ll_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (epc.equals("")) {
                    Toastor.getInstance().showShortToast("请先扫卡");
                    return;
                } else if (FItemID == 0) {
                    Toastor.getInstance().showShortToast("请选择新产品");
                    return;
                } else if (tv_epc_new.getText().toString().equals("")) {
                    Toastor.getInstance().showShortToast("请扫描新卡");
                    return;
                }
                HashMap<String, Object> param = new HashMap<String, Object>();
                param.put("epc", epc);
                param.put("epc_new", tv_epc_new.getText().toString());
                param.put("FItemID", FItemID);
                HttpRequest httpRequest = new HttpRequest(mContext, WebApi.production(), "postChangeProduct", JSON.toJSONString(param), true, true);
                httpRequest.send(new SimpleHttpListener<JSONObject>() {
                    @Override
                    public void onSucceed(int what, Response<JSONObject> response) {
                        super.onSucceed(what, response);
                        Toastor.getInstance().showShortToast("保存成功");
                        clear();
                    }
                });

            }
        });
    }

    private void clear(){
        epc = "";
        FItemID = 0;
        tv_epc.setText("");
        tv_FName.setText("");
        tv_FNumber.setText("");
        tv_FQty.setText("");
        tv_FModel.setText("");
        tv_epc_new.setText("");
        at_FNumber_new.setText("");
        tv_FName_new.setText("");
        tv_FModel_new.setText("");
        tv_FGongxuName.setText("");
    }


    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            if (epc.equals("")) {
                getProductInfo(m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", ""));
            } else if (!m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "").equals(epc)){
                tv_epc_new.setText(m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", ""));
            } else {
                Toastor.getInstance().showShortToast("卡号："+m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "")+"\n已扫描");
            }
        }
    }

    /**
     * 获取产品信息
     */
    private void getProductInfo(String strepc){
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", strepc);
        param.put("FActionFlag", "changeProduct");
        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.production(), "getProductInfo", JSON.toJSONString(param), true, true);
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                JSONObject data = response.get().optJSONObject("data");
                epc = data.optString("epc");
                tv_epc.setText(data.optString("epc"));
                tv_FName.setText(data.optString("FName"));
                tv_FNumber.setText(data.optString("FNumber"));
                tv_FQty.setText(String.valueOf(data.optDouble("FQty")));
                tv_FModel.setText(data.optString("FModel"));
                tv_FGongxuName.setText(data.optString("FGongxuName"));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            at_FNumber_new.setText(data.getStringExtra("FNumber"));
            tv_FName_new.setText(data.getStringExtra("FName"));
            tv_FModel_new.setText(data.getStringExtra("FModel"));
            FItemID = data.getIntExtra("FItemID", 0);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!epc.equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
